import facade
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "isbn_cover", "download", "isbncover")
BaseDir.create_dir(sPath)


class DownCover(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=self.logger)

    def down_cover(self):
        sql = "select isbn13,isbn10,url from isbncover where stat=1 and url != '-1' and coverstat=0 order by rand() limit 1000"
        rows = self.mysqlutils.SelectFromDB(sql)
        if not rows:
            return "break"
        for row in rows:

            isbn13 = row[0].lower()
            isbn10 = row[1].lower()
            # isbn13 路径
            coverpath13 = BaseDir.get_new_path(sPath, "isbn13", isbn13[:9])
            path13 = BaseDir.get_new_path(coverpath13, isbn13 + ".jpg")
            # isbn10 路径
            coverpath10 = BaseDir.get_new_path(sPath, "isbn10", isbn10[:6])
            path10 = BaseDir.get_new_path(coverpath10, isbn10 + ".jpg")
            if BaseDir.is_file_exists(path13) and BaseDir.is_file_exists(path10):
                sql = "update isbncover set coverstat=1 where isbn13='{}'".format(isbn13)
                self.mysqlutils.ExeSqlToDB(sql)
                self.logger.info("文件存在")
                continue
            BoolResult, errString, r = facade.BaseRequest(row[2], endstring='')
            if BoolResult:
                BaseDir.create_dir(coverpath13)
                BaseDir.create_dir(coverpath10)
                ImageFile.save_img_to_jpg(r.content, path13)
                ImageFile.save_img_to_jpg(r.content, path10)
                sql = "update isbncover set coverstat=1 where isbn13='{}'".format(isbn13)
                self.mysqlutils.ExeSqlToDB(sql)
            else:
                if r is not None and r.status_code == 404:
                    sql = "update isbncover set coverstat=-1 where isbn13='{}'".format(isbn13)
                    self.mysqlutils.ExeSqlToDB(sql)
                self.logger.info("下载错误,请检查")


if __name__ == "__main__":
    down = DownCover()
    while True:
        results = down.down_cover()
        if results == "break":
            break
